-- Remove access token 
-- Written by Kevin.XU
-- 2016/7/25

--[[
Request body:::
{
    "service_type":"SHOPPING",
    "token":"eyJleHBpcmVfdGltZSI6MTQ2OTE4OTMxMSwibWVtYmVyX2xldmVsIjoiMSIsImxvZ2luX2F1dGgiOiJqYWNrIiwidmFsaWRpdHkiOjMwLCJjbGllbnRfaXAiOiIxMTIuMTEuMS4xMCIsImNsaWVudF90eXBlIjoiaXBob25lIn0="
}
Response body:::
{
    "status":0,
    "status_desc":""
}
]]

ngx.req.read_body()

local resty_redis = require "resty.redis"
local resty_cjson = require "cjson"
local resty_md5 = require "resty.md5"
local resty_string = require "resty.string"
local limit_toolkit = require "ddtk.limit_tk"
local redis_config = require "ddtk.redis_config"
local syncr_config = require "ddtk.syncr_config"
local syncr = require "libsyncr" 

local max_idle_timeout = 300*1000
local pool_size = 20
local timeout = 1000

--make response
local resp={}

--read request body and make token value
local now=os.time()
local json_request_body_data = ngx.req.get_body_data()
local request_body = resty_cjson.decode(json_request_body_data) 
local service_type = request_body.service_type
local token_value = request_body.token

local tkey_hex = limit_toolkit.md5(token_value)
if not tkey_hex then
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    return
end

--get redis address
local redis_ip,redis_port = redis_config.select_master_redis_node(service_type)
if redis_ip == nil then
    ngx.log(ngx.ERR, "not found redis")
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    return
end
local red = resty_redis:new()
red:set_timeout(timeout)
local ok, err = red:connect(redis_ip, redis_port)
if not ok then
    ngx.log(ngx.ERR, "connect failed")
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    return
end
--try to remove token value from redis
local res, err2 = red:del(tkey_hex)
if res > 0 then
    local command = "del " .. tkey_hex
    ok, err = syncr.sync_command(syncr_config.get_msgid(service_type),command)
    if not ok then
        red:set_keepalive(max_idle_timeout, pool_size)
        ngx.log(ngx.ERR, "sync failed")
        ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
        return
    end
    resp['status']=0
    resp['status_desc']=''
else
    resp['status']=1
    resp['status_desc']='Not found token'
end

--keep connection alive
red:set_keepalive(max_idle_timeout, pool_size)


local resp_json = resty_cjson.encode(resp) 

ngx.say(resp_json)
